<template>
  <div class="app-container">
    <div id="map"></div>
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="归属区域">
        <el-input v-model="queryParams.regionName" placeholder="请输入归属区域" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="归属门店" prop="storeName">
        <el-input v-model="queryParams.storeName" placeholder="请输入归属门店" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="联系电话" prop="phoneNumber">
        <el-input v-model="queryParams.phoneNumber" placeholder="请输入联系电话" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery"
          v-hasPermi="['business:storeCard:query']">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['business:storeCard:add']">新增</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-download" size="mini" @click="handleImport"
          v-hasPermi="['business:storeCard:add']">导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-upload2" size="mini" @click="handleExport">导出</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['business:storeCard:edit']"
          >修改</el-button
        >
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-setting" size="mini" :disabled="multiple" @click="handleGive"
          v-hasPermi="['business:storeCard:give']">赠送优惠券</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['business:storeCard:del']">删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table v-loading="loading" :data="storeList" max-height="650px" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="序号" align="center" prop="id"  width="120"/> -->

      <el-table-column label="归属区域" align="center" prop="regionName" />
      <el-table-column label="归属门店" align="center" prop="storeName" />

      <el-table-column label="客户姓名" align="center" prop="userName" />
      <el-table-column label="性别" align="center" prop="gender">
        <template slot-scope="scope">
          <span>{{
            scope.row.gender == 0 ? "男" : scope.row.gender == 1 ? "女" : "未知"
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="电话" align="center" prop="phoneNumber" />
      <el-table-column label="生日" align="center" prop="dateOfBirth" />
     <el-table-column label="消费频次" align="center" prop="consumptionFrequency" >
      
      <template slot-scope="scope">
          <span v-if="scope.row.consumptionFrequency<3">低频</span>
          <span v-if="scope.row.consumptionFrequency<7 && scope.row.consumptionFrequency>2">中频</span>
          <span v-if="scope.row.consumptionFrequency>6">高频</span>
        </template>

      </el-table-column>


      <!-- <el-table-column
        label="储值卡编号"
        align="center"
        prop="id"
        width="200"
      /> -->
      <el-table-column label="卡名称" align="center" prop="ruleName" width="200" />
      <el-table-column label="充值金额" align="center" prop="principal" />

      <el-table-column label="实付金额" align="center" prop="actuallyMoney" />
      <el-table-column label="赠送方式" align="center" prop="" >
        <template slot-scope="scope">
          <span>{{
            scope.row.couponNumber > 0 ? "赠送优惠券" :  "赠送金额"
          }}</span>
        </template>
      </el-table-column>

      <el-table-column label="赠送金额" align="center" prop="gift" />

      <el-table-column label="优惠券名称" :show-overflow-tooltip="true"  align="center" prop="couponName" />
      <el-table-column label="优惠券数量" align="center" prop="couponNumber" />

      <el-table-column label="适用门店"     :show-overflow-tooltip="true" align="center" prop="stores" />
      <el-table-column label="折扣" align="center" prop="discountRate" />


      <el-table-column label="支付方式" align="center" prop="paymentType">
        <template slot-scope="scoped">
          <div>
            {{
              (moneyConfig[scoped.row.paymentType] || moneyConfig["default"])
                .text
            }}
          </div>
        </template>
      </el-table-column>


      <el-table-column label="提成技师" align="center" prop="referrerName" width="200" />


      <el-table-column label="状态" align="center" prop="cardStatus" width="120">
        <template slot-scope="scope">
          <!-- 0 禁用 1 启用  2 退卡 -->
          <span>{{
            scope.row.cardStatus == 0
              ? "禁用"
              : scope.row.cardStatus == 1
                ? "启用"
                : "退卡"
          }}</span>
        </template>
      </el-table-column>


      <el-table-column label="创建人" align="center" prop="createBy" />
      <el-table-column label="创建时间" align="center" prop="createTime" />


      <el-table-column label="修改人" align="center" prop="updateBy" />
      <el-table-column label="修改时间" align="center" prop="updateTime" />

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="280">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-view" @click="queryConsumptionList(scope.row)"
            v-hasPermi="['business:storeCard:edit']">消费记录</el-button>
          <span v-if="scope.row.cardStatus != 2">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
              v-hasPermi="['business:storeCard:calendar']">修改</el-button>
            <el-button size="mini" type="text" icon="el-icon-upload2" @click="handleGround(scope.row, (cardStatus = 1))"
              v-hasPermi="['business:storeCard:open']" :disabled="scope.row.cardStatus === 1">启用</el-button>
            <el-button size="mini" type="text" icon="el-icon-download"
              @click="handleGround(scope.row, (cardStatus = 0))" v-hasPermi="['business:storeCard:disabled']"
              :disabled="scope.row.cardStatus === 0">禁用</el-button>
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleRenew(scope.row)"
              v-hasPermi="['business:storeCard:renew']">续费</el-button>

            <el-button size="mini" type="text" icon="el-icon-sell" @click="handleRefund(scope.row)"
              v-hasPermi="['business:storeCard:returnCard']">退卡</el-button>
          </span>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['business:storeCard:del']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />
    <!-- 添加或修改门店对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="150px">
        <el-form-item label="储蓄卡编号" prop="id" v-if="title == '储蓄卡充值'">
          <el-input v-model="form.id" placeholder="请输入会员卡编号" :disabled="title == '修改储蓄卡' || title == '储蓄卡充值'" />
        </el-form-item>
        <!-- <el-form-item label="创建时间" prop="createTime" v-if='title == "储蓄卡充值"'>
              <el-input v-model="form.createTime" placeholder="请输入创建时间" />
            </el-form-item> -->
        <el-form-item label="归属区域" prop="regionId">
          <el-select clearable v-model="form.regionId" @change="changeRegion"
            :disabled="title == '修改储蓄卡' || title == '储蓄卡充值'">
            <el-option v-for="(item, index) of region" :key="index" :label="item.value" :value="item.key">{{ item.value
            }}</el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="归属门店" prop="storeId">
          <el-select clearable v-model="form.storeId" @change="changeStore"
            :disabled="title == '修改储蓄卡' || title == '储蓄卡充值'">
            <el-option v-for="(item, index) of store" :key="index" :label="item.value" :value="item.key">{{ item.value
            }}</el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="客户电话" prop="userId">
          <el-select clearable v-model="form.phoneNumber" allow-create filterable @change="changephoneNumber"
            :disabled="title == '修改储蓄卡' || title == '储蓄卡充值'">
            <el-option v-for="(item, index) of userNamelist" :key="index" :label="item.value" :value="item.key">{{
              item.value }}</el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="客户姓名" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入客户姓名" :disabled="title == '修改储蓄卡' || title == '储蓄卡充值'"
            style="width: 222px" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select clearable v-model="form.gender" :disabled="title == '修改储蓄卡' || title == '储蓄卡充值'">
            <el-option v-for="(item, index) of gender" :key="index" :label="item.value" :value="item.key">{{ item.value
            }}</el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="出生年月" prop="dateOfBirth">
          <el-date-picker clearable v-model="form.dateOfBirth" type="date" :picker-options="pickerOptions"
            :disabled="title == '修改储蓄卡' || title == '储蓄卡充值'" value-format="yyyy-MM-dd" placeholder="请选择出生年月">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="规则类型" prop="ruleId" v-if="
          title == '添加储蓄卡' ||
          title == '储蓄卡充值' ||
          title == '修改储蓄卡'
        ">
          <el-select clearable v-model="form.ruleId" @change="changeRules" no-match-text="请选择规则类型">
            <el-option v-for="(item, index) of Rule" :key="index" :label="item.value" :value="item.key">{{ item.value
            }}</el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="原储蓄卡类型" prop="ruleId" v-if="title == '储蓄卡充值'">
          <el-select clearable v-model="ruleId1" disabled>
            <el-option v-for="(item, index) of Rule" :key="index" :label="item.value" :value="item.key">{{ item.value
            }}</el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="充值金额" prop="principal" v-show="title == '修改储蓄卡' || isAdd">
          <!-- :disabled="title == '修改储蓄卡'" -->
          <el-input type="number" disabled v-model="form.principal" placeholder="请输入价格" style="width: 222px"
            @input="changePrincipal" />
        </el-form-item>
        <!-- <el-form-item label="充值金额" prop="newPrincipal" v-if='title == "储蓄卡充值"'>
          <el-input v-model="form.newPrincipal" placeholder="请输入价格" style="width: 222px;" />
        </el-form-item> -->
        <el-form-item label="赠送金额" prop="gift" v-show="title == '修改储蓄卡' || isAdd">
          <el-input v-model="form.gift" placeholder="请输入赠送金额" :disabled="title !== '储蓄卡充值'" style="width: 222px"
            :key="isInput" />
        </el-form-item>
        <el-form-item label="推荐人" prop="referrerName">
          <el-select clearable v-model="form.referrerId" filterable>
            <el-option v-for="(item, index) of jishi" :key="index" :label="item.value" :value="item.key">{{ item.value
            }}</el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="赠送金额" prop="newGift" v-if='title == "储蓄卡充值"'>
          <el-input v-model="form.newGift" placeholder="请输入赠送金额" style="width: 222px;" />
        </el-form-item> -->
        <el-form-item label="实付金额" prop="actuallyMoney" v-if="title == '添加储蓄卡'">
          <el-input type="number" v-model="form.actuallyMoney" placeholder="请输入实付金额" style="width: 222px" />
        </el-form-item>
        <el-form-item label="支付方式" prop="paymentType">
          <el-select clearable v-model="form.paymentType" @change="paymentTypeChange" :disabled="title == '修改储蓄卡'">
            <el-option v-for="(item, index) of money" :key="index" :label="item.value" :value="item.key">{{ item.value
            }}</el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="条形码" prop="payCode" v-if="isInput">
          <el-input v-model="form.payCode" placeholder="请输入条形码" @change="handleScanCode" ref="code"
            style="width: 222px"></el-input>
        </el-form-item>
        <el-form-item label="团购劵" prop="payCode" v-if="isGroup">
          <el-input v-model="form.tgj" placeholder="请输入团购劵码" style="width: 222px"></el-input>
        </el-form-item>
        <el-form-item label="实付金额" prop="payCode" v-if="isGroup">
          <el-input v-model="form.sfje" type="number" placeholder="请输入实付金额" style="width: 222px"></el-input>
        </el-form-item>
        <!-- <el-form-item label="支付方式" prop="paymentType">
          <el-select clearable v-model="form.paymentType">
					<el-option v-for="(item,index) of money" :key="index" :label="item.value" :value="item.key">{{item.value}}</el-option>
				</el-select>
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 赠送优惠券弹框 -->
    <el-dialog :title="title" :visible.sync="giveDialog" width="1150px" append-to-body :close-on-click-modal="false">
      <el-table v-loading="loading" :data="couponList" @selection-change="handleGiveChange">
        <el-table-column type="selection" width="55" align="center" />
        <!-- <el-table-column label="序号" align="center" prop="storeName" /> -->
        <el-table-column label="优惠券名称" align="center" prop="name" width="120" />
        <el-table-column label="优惠券类型" align="center" prop="discountsType" width="120">
          <template slot-scope="scope">
            <span>{{ scope.row.discountsType == 1 ? '折扣券' : '立减券' }}</span>
          </template>
       </el-table-column>


        <el-table-column label="所属区域" align="center" prop="regionName" width="120">
          <template slot-scope="scope">
            <el-tooltip class="tooltip" placement="top">
              <div slot="content" style="max-width: 650px">
                {{
                  scope.row.regionName === null ? "无" : scope.row.regionName
                }}
              </div>
              <p class="descStyle">
                {{
                  scope.row.regionName === null ? "无" : scope.row.regionName
                }}
              </p>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="所属门店" align="center" prop="storeName">
          <template slot-scope="scope">
            <el-tooltip class="tooltip" placement="top">
              <div slot="content" style="max-width: 650px">
                {{ scope.row.storeName === null ? "无" : scope.row.storeName }}
              </div>
              <p class="descStyle">
                {{ scope.row.storeName === null ? "无" : scope.row.storeName }}
              </p>
            </el-tooltip>
          </template>
        </el-table-column>
        <!-- <el-table-column label="优惠券图片" align="center" prop="picture" width="160">
          <template slot-scope="scope">
            <image-preview :src="scope.row.picture" :width="50" :height="50" />
          </template>
        </el-table-column> -->
        <el-table-column label="优惠门槛" align="center" prop="fullAmount" width="120" />
        <el-table-column label="优惠金额" align="center" prop="discountAmount" width="120">
          <template slot-scope="scope">
            <span>{{
              scope.row.discountAmount ? scope.row.discountAmount : "暂无"
            }}</span>
          </template>
        </el-table-column>
        <!-- <el-table-column label="适用项目" align="center" prop="projectName"  width="120"/> -->
        <el-table-column label="适用项目" align="center" prop="projectName" width="200">
          <template slot-scope="scope">
            <el-tooltip class="tooltip" placement="top">
              <div slot="content" style="max-width: 600px">
                {{
                  scope.row.projectName === null ? "无" : scope.row.projectName
                }}
              </div>
              <div class="descStyle">
                {{
                  scope.row.projectName === null ? "无" : scope.row.projectName
                }}
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="使用周期" align="center" prop="useToday" width="120">
          <template slot-scope="scope">
            <span>{{ scope.row.useToday ? scope.row.useToday : "不限" }}</span>
          </template>
        </el-table-column>
        <el-table-column label="上架" align="center" prop="state" width="120">
          <template slot-scope="scope">
            <span>{{ scope.row.state == "1" ? "上架" : "下架" }}</span>
          </template>
        </el-table-column>

        <!-- <el-table-column label="优惠券类型" align="center" prop="state" width="120">
          <template slot-scope="scope">
            <span>{{
              scope.row.discountsType == "1" ? "折扣券" : "立减券"
            }}</span>
          </template>
        </el-table-column> -->
        <el-table-column label="创建时间" align="center" prop="createTime" width="160" />
      </el-table>
      <pagination v-show="total1 > 0" :total="total1" :page.sync="pageNum" :limit.sync="pageSize"
        @pagination="getCouponList" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="couponSubmit">确 定</el-button>
        <el-button @click="couponCancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- <el-dialog title="支付" :visible.sync="commonVisible" width="500px" append-to-body :close-on-click-modal="false"
      @close="closeCommonVisible">
      <div>
        <div class="pay-box">
          <div class="pay-item">
            支付方式：{{ payTypeConfig[orderForm.paymentType] }}
          </div>
          <div class="pay-item">
            实付金额：{{ actuallyMoney }}元
          </div>
          <div class="column-center">
            <el-input style="width: 200px;margin: 20px 0" v-model="scanCode" clearable placeholder="请输入支付码"
              @change="handleScanCode" ref="code"></el-input>
            <el-button type="primary" class="confirm-pay-btn" @click="clickSurePay">确定收款</el-button>
          </div>
        </div>
      </div>
    </el-dialog> -->
    <el-dialog title="消费记录" :visible.sync="isConsumCludes" width="850px" append-to-body :close-on-click-modal="false">
      <el-table v-loading="loading" :data="consumCludes" max-height="600px">
        <el-table-column label="订单号" align="center" prop="orderId" width="160" />
        <el-table-column label="消费门店" align="center" prop="storeName" />
        <el-table-column label="消费项目" align="center" prop="itemName" width="150" />
        <el-table-column label="消费金额(元)" align="center" prop="sumMoney" width="120" />
        <el-table-column label="消费时间" align="center" prop="createTime" width="100" />
        <el-table-column label="技师" align="center" prop="technicianName"></el-table-column>
        <el-table-column label="状态" align="center" prop="detailType">
          <template slot-scope="scope">
            <span>{{ detailTypeList[scope.row.detailType - 1] }}</span>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total2 > 0" :total="total2" :page.sync="consum.pageNum" :limit.sync="consum.pageSize"
        @pagination="getCar" />
    </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <!-- <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据
          </div> -->
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline"
            @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogVisible" title="系统提示">
      <div>
        <p>经计算将退还卡剩余金额 <el-input v-model="dialogRow.money" style="width: 100px;"
            placeholder="退还金额"></el-input>元；确定要退卡吗？（参考比例：{{ dialogRow.refundRatio }}%）</p>

      </div>
      <div slot="footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmRefund">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listCard,
  listCardRule,
  getCard,
  delCard,
  addCard,
  updateCard,
  listChina,
  listResetPwd,
  getCardContinue,
  listnormalList,
  listMemberRegion,
  addMemberContinueCard,
  listMemberStore,
  listMemberUser,
  refundCardInfo,
  refundCard,
} from "@/api/system/card/storeCard";

import { giveUserCoupon } from "@/api/system/card/memCard";
import { listCardDetail } from "@/api/system/card/storeCardDetail";
import { getToken } from "@/utils/auth";
import {
  listcoupon,
  cardDetailList,
  getZyCouponEffectiveList,
} from "@/api/system/coupon/couponList";
export default {
  name: "Store",
  data() {
    return {
      dialogVisible: false, // 退款确认对话框
      refundAmount: "", // 退款金额
      dialogRow: {
        money: "", // 退款金额
        refundRatio: "", // 退款比例
        // cardId: "", // 卡id
      }, // 退款数据
      map: null,
      local: null,
      mk: null,
      latitude: "",
      longitude: "",
      keyWords: "",
      result: "",
      ruleId1: "",
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 门店表格数据
      storeList: [],
      //优惠券列表数据
      couponList: [],
      // 弹出层标题
      title: "",
      // money:[
      //   {key: 1,value: '微信'},
      // 	{key: 2,value: '支付宝'},
      //   {key: 3,value: '现金'},
      //   {key: 4,value: '银行卡'},
      //   {key: 5,value: '其他'},
      // ],
      // 是否显示弹出层
      open: false,
      // 导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url:
          process.env.VUE_APP_BASE_API + "/system/value/card/batchImportClue",
      },

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        regionName: null,
        storeName: null,
        phoneNumber: null,
        // province: null,
        // provinceString: null,
        // city: null,
        // cityString: null,
        // county: null,
        // countyString: null,
        // detail: null,
        // longitude: null,
        // latitude: null,
        // intro: null,
        // images: null,
        // status: null,
        // isInitiate: null,
        // openingTime: null,
        // closingTime: null,
        // gender: null,
        // dateOfBirth: null,
        // paymentType: null,
      },
      pageNum: 1,
      pageSize: 10,
      total1: 0,
      // 表单参数
      form: {
        actuallyMoney: "",
      },
      // 表单校验
      rules: {
        actuallyMoney: [
          { required: true, message: "请输入实付金额", trigger: "blur" },
        ],
        paymentType: [{ required: true, message: "请选择支付方式", trigger: "blur" }],
      },
      options: [],
      List: [
        {
          key: 1,
          value: "营业中",
        },
        {
          key: 2,
          value: "未营业",
        },
      ],
      gender: [
        {
          key: 0,
          value: "男",
        },
        {
          key: 1,
          value: "女",
        },
        {
          key: 2,
          value: "未知",
        },
      ],
      money: [
        // { key: 1, value: "微信" },
        // { key: 2, value: "支付宝" },
        { key: 3, value: "现金" },
        // { key: 4, value: "银行卡" },
        // { key: 5, value: "店铺储蓄卡" },

        { key: 7, value: "扫码支付" },
        { key: 6, value: "其他" },
        // { key: 8, value: "团购券" },
      ],
      moneyConfig: {
        1: { text: "微信" },
        2: { text: "支付宝" },
        3: { text: "现金" },
        4: { text: "银行卡" },
        5: { text: "店铺储蓄卡" },
        6: { text: "其他" },
        7: { text: "扫码支付" },
        8: { text: "团购券" },
        default: { text: "--" },
      },
      region: [],
      store: [],
      Rule: [],
      userNamelist: [],
      jishi: [],
      disabled: false,
      isAdd: false,
      commonVisible: false,
      isInput: false,
      isGroup: false,
      isConsumCludes: false,
      consumCludes: [],
      consum: {
        carId: null,
        pageNum: 1,
        pageSize: 10,
      },
      total2: 0,
      //是否赠送优惠券弹框
      giveDialog: false,
      giveIds: [],
      userIds: [],
      id: "",
      carId: "",
      detailTypeList: ["充值", "消费", "退卡", "转赠", "退款"],
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        },
      },
    };
  },
  created() {
    this.getList();
    this.listregion();
    // this.listCardRule()
    this.getListMemberUser();

    // listnormalList().then((res) => {
    //   this.jishi = res.data.map((rItem) => {
    //     return {
    //       key: rItem.id,
    //       value: rItem.name,
    //     };
    //   });
    // });
  },
  methods: {
    queryConsumptionList(item) {
      this.consum.carId = item.id;
      this.consum.pageNum = 1;
      this.getCar();
    },
    getCar() {
      cardDetailList(this.consum).then((res) => {
        this.consumCludes = res.rows;
        this.total2 = res.total;
        this.isConsumCludes = true;
      });
    },

    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      location.href =
        "https://www.sczyjk.top/prod-api/profile/upload/importmodel/储蓄卡导入模板.xlsx";
      // this.download('system/user/importTemplate', {
      // }, `user_template_${new Date().getTime()}.xlsx`)
    },

    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
        response.msg +
        "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },

    //支付方式变更
    paymentTypeChange(e) {
      console.log("支付方式-->", e);
      if (e == 7) {
        this.isInput = true;
        this.$nextTick(() => {
          this.$refs.code.focus();
        });
        // } else {
        //   this.isInput = false
      }
    },
    //监听扫码枪
    handleScanCode(event) {
      console.log("回车事件--->", event);
      this.$modal.msgSuccess("扫码成功，请点击确认收款");
      this.form.payCode = event;
    },
    listregion() {
      listMemberRegion().then((res) => {
        this.region = res.data.map((rItem) => {
          return {
            key: rItem.id,
            value: rItem.regionName,
          };
        });
      });
    },
    getListMemberStore(regionId) {
      const params = { regionId };
      listMemberStore(params).then((res) => {
        this.store = res.data.map((rItem) => {
          return {
            key: rItem.id,
            value: rItem.storeName,
          };
        });
      });
    },

    //获取充值金额
    changePrincipal() {
      this.form.actuallyMoney = this.form.principal;
    },
    // 获取规则列表
    async getListCardRule(regionId) {
      const params = { regionId, status: 1 };
      let res = await listCardRule(params);
      if (res.code == 200) {
        this.Rule = res.rows.map((rItem) => {
          console.log(rItem);
          return {
            key: rItem.id,
            value: rItem.ruleName,
            discountRate: rItem.discountRate,
            principal: rItem.topUp,
            gift: rItem.gift,
          };
        });
        if (this.title == "储蓄卡充值") {
          this.changeRules(this.form.ruleId);
        }
        return res;
      }
    },
    getListMemberUser() {
      listMemberUser().then((res) => {
        this.userNamelist = res.rows.map((rItem) => {
          return {
            key: rItem.id,
            value: rItem.phoneNumber,
            userName: rItem.userName,
            gender: rItem.sex,
            birthday: rItem.birthday,
          };
        });
      });
    },
    changeRegion(value) {
      const selectedOption = this.region.find((item) => item.key === value);
      if (selectedOption) {
        this.form.regionName = selectedOption.value;
        this.form.storeId = "";
      } else {
        this.form.storeId = null;
        this.form.storeName = "";
      }

      this.getListMemberStore(value);
      this.getListCardRule(value);
    },
    changeStore(value) {
      const selectedOption = this.store.find((item) => item.key === value);
      if (selectedOption) {
        this.form.storeName = selectedOption.value;
      }
      listnormalList({ belongStoreId: value }).then((res) => {
        this.jishi = res.data.map((rItem) => {
          return {
            key: rItem.id,
            value: rItem.name,
            gender: rItem.gender,
          };
        });
      });
    },
    closeCommonVisible() {
      this.commonVisible = false;
    },
    changephoneNumber(value) {
      const selectedOption = this.userNamelist.find(
        (item) => item.key === value
      );
      if (selectedOption) {
        this.form.phoneNumber = selectedOption.value;
        this.form.userName = selectedOption.userName;
        this.form.gender = selectedOption.gender;
        this.form.birthday = selectedOption.birthday;
        this.form.dateOfBirth = selectedOption.birthday;
      }
    },
    changeRules(value) {
      if (this.title == '修改储蓄卡') return
      this.isAdd = true;

      let item = this.Rule.findLast((item) => item.key == value);
      this.form.principal = item.principal;
      this.form.actuallyMoney = item.principal;
      this.form.gift = item.gift;
      this.form.discountRate = item.discountRate;
      // this.form.actuallyMoney = item.actuallyMoney;
      // this.$set(this.form, principal, item.principal)
      // this.$set(this.form, gift, item.gift)
      // this.$set(this.form, discountRate, item.discountRate)

      // if (item.key === value) {
      //   this.form.principal = item.principal
      //   this.form.gift = item.gift
      //   this.form.discountRate = item.discountRate
      // }
    },
    //点击赠送优惠券
    handleGive(row) {
      this.giveDialog = true;
      this.title = "赠送优惠券";
      this.id = row.id;
      this.getCouponList();
    },
    //优惠券列表
    getCouponList() {
      this.loading = true;
      const params = {
        pageSize: this.pageSize,
        pageNum: this.pageNum,
        getPath: 3,
        state: 1,
      };
      getZyCouponEffectiveList(params).then((response) => {
        this.couponList = response.rows;
        this.total1 = response.total;
        this.loading = false;
      });
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.getCouponList();
    },
    handleCurrentChange(val) {
      this.pageNum = val;
      this.getCouponList();
    },
    //赠送优惠券
    couponSubmit() {
      if(this.giveIds==''){
        this.$modal.msgError('您没有选择任何优惠券');
        return false;
      }
      const params = {
        userIds: this.userIds,
        couponIds: this.giveIds,
      };
      giveUserCoupon(params).then((response) => {
        if (response.code == 200) {
          this.giveDialog = false;
          this.$message.success(response.msg);
          this.getCouponList();
          this.getList();
        }
      });
    },
    //取消赠送
    couponCancel() {
      this.giveDialog = false;
    },
    //赠送优惠券多选
    handleGiveChange(selection) {
      this.giveIds = selection.map((item) => item.id).join(",");
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 查询门店列表 */
    getList() {
      this.loading = true;
      listCard(this.queryParams).then((response) => {
        this.storeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.isAdd = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        actuallyMoney: null,
        payCode: null,
        storeName: null,
        phoneNumber: null,
        province: null,
        provinceString: null,
        city: null,
        cityString: null,
        county: null,
        countyString: null,
        detail: null,
        longitude: null,
        latitude: null,
        intro: null,
        images: null,
        status: null,
        userName: null,
        isInitiate: null,
        openingTime: null,
        closingTime: null,
        createTime: null,
        updateTime: null,
        principal: null,
        gift: null,
        birthday: null,
        gender: null,
        dateOfBirth: null,
        paymentType: null,
        regionId: null,
        storeId: null,
        ruleId: null,
        referrerId: null,
        tgj: null,
        sfje: null,
      };
      this.ruleId1 = null;
      this.jishi = []
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      // this.resetForm("queryForm");
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        regionName: null,
        storeName: null,
        phoneNumber: null,
      };
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.userIds = selection.map((item) => item.userId).join(",");
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加储蓄卡";
      this.isInput = false;
    },
    // 上下架
    handleGround(row, cardStatus) {
      const params = {
        id: row.id,
        cardStatus: cardStatus,
      };
      this.$confirm(
        `此操作将${cardStatus === 1 ? "启用" : "禁用"}该数据, 是否继续?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          updateCard(params).then((res) => {
            this.$message({
              type: "success",
              message: `${cardStatus === 1 ? "启用" : "禁用"}成功!`,
            });
            this.getList();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消",
          });
        });
    },
    handleRenew(row) {
      this.reset();
      const id = row.id || this.ids;
      getCardContinue(id).then((response) => {
        this.form = response.data;
        this.ruleId1 = this.form.ruleId;

        this.open = true;
        this.title = "储蓄卡充值";
        this.getListMemberStore(row.regionId);
        this.getListCardRule(row.regionId);
        this.changeStore(row.storeId);
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getCard(id).then(async (response) => {
        this.form = response.data;
        this.open = true;
        this.getListMemberStore();
        this.title = "修改储蓄卡";
        if ((this.title = "修改储蓄卡")) {
          this.disabled = true;
        }
        this.changeStore(response.data.storeId);
        await this.getListCardRule(this.form.regionId);
        // 判断规则列表中是否有请求中返回的规则数据
        let findData = this.Rule.find((item) => item.key == this.form.ruleId);
        if (!findData) {
          this.form.ruleId = null;
        }
      });
    },

    /** 提交按钮 */
    submitForm() {
      console.log(this.form, "form222");
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.title == "修改储蓄卡") {
            updateCard(this.form).then((response) => {
              this.form.payCode = "";
              if (response.code == 200) {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              } else {
                this.$nextTick(() => {
                  this.$refs.code.focus();
                });
              }
            });
          } else if (this.title == "储蓄卡充值") {
            addMemberContinueCard(this.form).then((response) => {
              this.form.payCode = "";
              if (response.code == 200) {
                this.$modal.msgSuccess("充值成功");
                this.open = false;
                this.getList();
              } else {
                this.$nextTick(() => {
                  this.$refs.code.focus();
                });
              }
            });
          } else if (this.title == "添加储蓄卡") {
            // 默认启用
            this.form.cardStatus = 1;
            addCard(this.form).then((response) => {
              this.form.payCode = "";
              if (response.code == 200) {
                this.$modal.msgSuccess("新增成功");
                this.isAdd = false;
                this.open = false;
                this.getList();
              } else {
                this.$nextTick(() => {
                  this.$refs.code.focus();
                });
              }
            });
          }
        }
      });
    },
    handReset(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认重置编号为"' + ids + '"的数据项？')
        .then(function () {
          return listResetPwd({ userId: ids });
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("重置成功");
        })
        .catch(() => { });
    },

    /** 退卡 */
    handleRefund(row) {
      const params = {
        id: row.id,
      };
      let _this = this;
      let refundMoney = Number(row.principal * (Number(row.refundRatio) / Number(100))).toFixed(2);
      this.dialogRow = {
        id: row.id,
        money: refundMoney,
        refundRatio: row.refundRatio,
      };
      this.dialogVisible = true;
      // this.dialogRow.money = refundMoney;

      // refundCardInfo(params).then((response) => {
      //   this.dialogVisible = true;
      //   this.dialogRow = response.data;
      //   this.dialogRow.rowId = row.id;
      // this.$modal
      //   .confirm(
      //     "经计算将退还卡剩余金额" +
      //     response.data.money +
      //     "元；确定要退卡吗？"
      //   )
      //   .then(function () {
      //     let obj = {
      //       cardId: row.id,
      //       money: response.data.money,
      //       way: 2,
      //     };
      //     _this.cardWithdrawal(obj);
      //   })
      //   .then(() => { })
      //   .catch(() => { });
      // });
    },
    confirmRefund() {
      let obj = {
        cardId: this.dialogRow.id,
        money: this.dialogRow.money,
        way: 2,
      };
      this.cardWithdrawal(obj);
    },
    cardWithdrawal(obj) {
      refundCard(obj).then((response) => {
        if (response.code == 200) {
          this.$modal.msgSuccess("操作成功");
          this.dialogVisible = false;
        }
        this.getList();
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除储值卡编号为"' + ids + '"的数据项？')
        .then(function () {
          return delCard(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "/system/value/card/export",
        {
          ...this.queryParams,
        },
        `store_${new Date().getTime()}.xlsx`
      );
    },
  },
  watch: {
    "form.paymentType": {
      handler(val) {
        switch (val) {
          case 7:
            this.isInput = true;
            this.isGroup = false;
            break;
          case 8:
            this.isInput = false;
            this.isGroup = true;
            break;
          default:
            this.isInput = false;
            this.isGroup = false;
            break;
        }
      },
    },
  },
};
</script>
<style>
.descStyle {
  width: 100px;
  white-space: nowrap;
  /* 防止文本换行 */
  overflow: hidden;
  /* 隐藏溢出的内容 */
  text-overflow: ellipsis;
  /* 溢出时显示省略号 */
}
</style>
